import * as adDataService from '../services/adData';
export default {
  namespace: 'adData',
  state: {
    list: [],
    packetList: [],
    materialList: [],
    totalCount: 0,
    summaryList: [],
    summaryListMain: [],
    summaryTotlelist: [],
    packetSummary: []
  },
  reducers: {
    save(state, { payload: { list, totalCount, summaryListMain} }) {
    	return { ...state, list, totalCount, summaryListMain };
    },
    savePacket(state, { payload: { packetList, packetSummary} }) {
      return { ...state, packetList, packetSummary };
    },
    saveMaterial(state, { payload: { materialList} }) {
      return { ...state, materialList };
    },
    saveSummary(state, {payload: { summaryTotlelist, summaryList }}) {
      return { ...state, summaryTotlelist, summaryList };
    }
  },
  effects: {
    *fetch({ payload }, { call, put }) {
    	const { data } = yield call(adDataService.fetch, { payload });
    	if (data) {
        const result = data.data;
        let summaryList = [];
        summaryList.push(result.summary);
    		yield put({
	    		type: 'save',
	    		payload: {
	    			list: result.list,
            totalCount: result.totalCount,
            summaryListMain: summaryList
	    		}
	    	});
    	}
    },
    *fetchPacket({ payload }, { call, put }) {
    	const { data } = yield call(adDataService.fetchPacket, { payload });
    	if (data) {
        const result = data.data;
        let packetSummary = [];
        packetSummary.push(result.summary);
    		yield put({
	    		type: 'savePacket',
	    		payload: {
	    			packetList: result.list,
            packetTotalCount: result.totalCount,
            packetSummary: packetSummary
	    		}
	    	});
    	}
    },
    *fetchMaterial({ payload }, { call, put }) {
    	const { data } = yield call(adDataService.fetchMaterial, { payload });
    	if (data) {
        const result = data.data;
    		yield put({
	    		type: 'saveMaterial',
	    		payload: {
	    			materialList: result.list
	    		}
	    	});
    	}
    },
    *summaryList ({payload}, { call, put }) {
      const { data } = yield call(adDataService.summaryList, { payload });
      if (data) {
        const result = data.data;
        let summaryList = [],
            newList = [];
        result.list.forEach(function( item, index ){
           item.index = index + 1;
           newList.push(item);
        });
        summaryList.push(result.summary);
    		yield put({
	    		type: 'saveSummary',
	    		payload: {
            summaryTotlelist: newList,
            summaryList: summaryList
	    		}
	    	});
    	}
    }
  },
  subscriptions: {

  }
};
